

const app = getApp()
const db = wx.cloud.database();
const _ = db.command;
//计数器
var interval = null;
var randmArr = [1, 5, 10, 20, 35, 55, 100, 100] //概率 8 格
var obj = { a1: 1, a2: 4, a3: 5, a4: 12, a5: 16, a6: 14, a7: 48, a8: 50 } //产生的随机数的次数
var form = {} //统计中奖的概率
//值越大旋转时间越长  即旋转速度
var intime = 20;
// 插屏广告
let interstitialAd = null;
Page({
  data: {
    shouquanfenzhi:true,
    id:'',//用于update
    loading: true,
    text:'在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。',
    openid: '889',
    userInfo: null,
    signNum: 0,
    signTime: '',
    luckNum: 10,
    jifen:0,
    desc:'啊实打实大苏打实打实大苏打实打实大苏打',//公告栏
    // 奖项及概率
    jp: ['传说皮肤自选一个', '国服陪玩局数*3', '勇者皮肤自选一个', '10点积分', '谢谢参与', '史诗皮肤自选一个', '50点积分', '国服陪玩局数*1'],
    gl: [0, 1, 0, 24, 65, 0, 5, 5],
    color: [1, 1, 1, 1, 1, 1, 1, 1],
    //9张奖品图片
    images: ['/images/zhuangpan/2.jpg', '/images/zhuangpan/wangzhe.jpg', '/images/zhuangpan/0.jpg', '/images/zhuangpan/jifen.jpg', '/images/zhuangpan/xiexiecanyu.png', '/images/houzi.jpg', '/images/zhuangpan/jifen.jpg', '/images/zhuangpan/wangzhe.jpg'],
    btnconfirm: '/images/zhuangpan/dianjichoujiang.png',
    clickLuck: 'clickLuck',
    //概率
    // randmArr: [1,5,10,20,35,55,100,100]
    // 中奖位置，0-7 从服务端获取????
    luckPosition: -1,
    luckPoint: 0,
    panduanuserinfo:false,
    avatarUrl:'',
    nickName: "",
  },

  onLoad: function () {
    console.log('load')
    this.loadAnimation();
  },
  onShow(){
    // this.getTaskCount()
   this.openid()//获取openid//和积分
   this.tongzhilan()
 
  },
  onHide(){
    this.setData({
      loading: true,
    })
  },
  //获取通知栏
  tongzhilan(){
    let text=''
db.collection('zp_price').where({}).orderBy('time_order','desc').get().then((res=>{
  console.log(res)
  for(let i=0;i<res.data.length;i++)
  {
    console.log(i)
    text=text+'恭喜'+'\t'+res.data[i].nickName+'\t'+'抽中'+'\t'+res.data[i].price_text+'&emsp;&emsp;&emsp;&emsp;'
  }
  this.setData({
    text:text
  })
}))
  },
//获取openid
openid(){
  let that = this
  wx.cloud.callFunction({
      name: 'openid'
  }).then(res => {                   
          db.collection('user').where({
            _openid:res.result.openid
          }).get().then((res=>{
            this.setData({
              loading: false,
            
            })
            if(res.data.length>0){
              this.setData({
                avatarUrl:res.data[0].avatarUrl,
                nickName: res.data[0].nickName,  
                id:res.data[0]._id,
                panduanuserinfo:true,
                jifen:res.data[0].jifen,
                luckNum:res.data[0].luckNum
              })
            }
          }))
      that.setData({
          openid: res.result.openid
      })  
  }).catch(err => {
      console.log(err)
  })
},
  // 抽奖 写库
  goodluck: function (point) {
    console.log("goodluck=" + point);
    let that = this;
    if(point!='谢谢参与')
{  
  if(point=='10点积分'|| point=='50点积分')
  {
    wx.cloud.callFunction({
        name: 'update',
        data: {
            action:'jifen',
            _id: that.data.id,
            jifen:that.data.jifen+parseInt(point)-5,
            luckNum:that.data.luckNum-1
        }
    }).then(res => { 
      db.collection('zp_price').add({
        data: {    
          price_text: point,
          avatarUrl:that.data.avatarUrl,
          nickName: that.data.nickName,
          time_order: new Date().getTime(),
        },
        success: res => {
          that.setData({
            jifen:that.data.jifen+parseInt(point)-5,
            luckNum:that.data.luckNum-1
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            title: '抽奖失败',
            icon: 'none'
          })
        }
      })
console.log('更新成功')
    })
  }
  else
  {
    wx.cloud.callFunction({
      name: 'update',
      data: {
          action:'jifen',
          _id: that.data.id,
          jifen:that.data.jifen-5,
          luckNum:that.data.luckNum-1
      }
  }).then(res => {
    db.collection('zp_price').add({
      data: {    
        price_text: point,
        avatarUrl:that.data.avatarUrl,
        nickName: that.data.nickName,
        time_order: new Date().getTime(),
      },
      success: res => {
        that.setData({
          jifen:that.data.jifen-5,
          luckNum:that.data.luckNum-1
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '抽奖失败',
          icon: 'none'
        })
      }
    })
   })

  }}
  else{
    wx.cloud.callFunction({
      name: 'update',
      data: {
          action:'jifen',
          _id: that.data.id,
          jifen:that.data.jifen-5,
          luckNum:that.data.luckNum-1
      }
  }).then(res => {
    that.setData({
      jifen:that.data.jifen-5,
      luckNum:that.data.luckNum-1
    })
  })
  }
  },
  input: function (e) {
    var data = e.detail.value;
    this.setData({
      luckPosition: data
    })
  },

  //点击抽奖按钮 渲染
  clickLuck: function () {
    var that = this;
    if(that.data.panduanuserinfo==true){
      console.log(that.data.luckNum)
      if ( that.data.luckNum <=0) {
        console.log("抽奖机会用完了！"); 
        wx.showToast({
          title: '抽奖机会用完了,明天再来吧！',
          icon: 'none'
        })
        return;
      } 
      else if(that.data.jifen<=0){
        console.log("积分不够啦！"); 
        wx.showToast({
          title: '积分不够啦！',
          icon: 'none'
        })
        return;
      }
      else {
        var luckPosition = that.choujiang();
        var jp = that.data.jp;
        console.log("中奖位置：" + luckPosition + "；奖品：" + jp[luckPosition])
        //设置按钮不可点击
        that.setData({
          luckPosition: luckPosition,//中奖位置
          luckPoint:jp[luckPosition],//奖品积分
          btnconfirm: '/images/zhuangpan/dianjichoujiangd.png',//点击图片
          clickLuck: '', //控制按钮
        })
        that.goodluck(jp[luckPosition]);
        //清空计时器
        clearInterval(interval);
        var index = 0;
        // console.log(that.data.color[0]);
        //循环设置每一项的透明度
        interval = setInterval(function () {
          if (index > 7) {
            index = 0;
            that.data.color[7] = 1
          } else if (index != 0) {
            that.data.color[index - 1] = 1
          }
          that.data.color[index] = 0.5
          that.setData({
            color: that.data.color,
          })
          index++;
        }, intime);
        //模拟网络请求时间  设为两秒
        var stoptime = 2000;
        setTimeout(function () {
          that.stop(luckPosition);
        }, stoptime)
      }
    }
    else
{   console.log(that.data.luckNum)
if(that.data.shouquanfenzhi==true)
  {
    that.setData({
      shouquanfenzhi:false
    })
    wx.getUserProfile({
        desc: '用于完善会员资料',
        success: (res) => {
          wx.showLoading({   
          })
            console.log(res.userInfo)
            let userInfo=res.userInfo
            that.setData({
              avatarUrl: userInfo.avatarUrl,
              nickName: userInfo.nickName,  
            })
            wx.cloud.database().collection('user').add({
              data: {
                avatarUrl: userInfo.avatarUrl,
                nickName: userInfo.nickName,    
                            jifen:100,
                            qiandaotype:false ,
                            luckNum:10
              },
              success(res) {                 
                      db.collection('user').where({
                        _openid:that.data.openid
                      }).get().then((res=>{
                        wx.hideLoading({
                         
                        })
                        that.setData({
                          loading: false,               
                        })
                        if(res.data.length>0){
                          that.setData({
                            avatarUrl:res.data[0].avatarUrl,
                            nickName: res.data[0].nickName,  
                            id:res.data[0]._id,
                            panduanuserinfo:true,
                            jifen:res.data[0].jifen,
                            luckNum:res.data[0].luckNum
                          })
                        }
                      }))           
             
              }})} ,complete: (res) => {
                console.log('complete')
                that.setData({
                  shouquanfenzhi:true
                })
              }
            
            })
      
            }
    }
  },


  // 根据位置的概率抽出一个位置id
  choujiang() {
    let gl = this.data.gl;
    var zs = 0;// 总数，如1-100
    var qj = new Array(8);// 区间
    for (var i in gl) {
      zs += gl[i];
      qj[i] = zs;
    }
    console.log(qj)
   console.log(zs);
    var sjs = parseInt(Math.random() * (zs) + 1);// 生成概率内的随机数
  console.log(sjs);
    var zjh = -1;// 中奖号
    for (var i in qj) {
     
      if (i > 0) {
       
        if (sjs > qj[i - 1] && sjs <= qj[i]) {
          zjh = i;
          break;
        }
      } else {
        console.log(i);
        if (sjs > 0 && sjs <= qj[i]) {
          zjh = i;
          break;
        }
      }
    }
    return zjh;
  },

  //也可以写成点击按钮停止抽奖
  // clickStop:function(){
  //   var stoptime = 2000;
  //   setTimeout(function () {
  //     e.stop(1);
  //   }, stoptime)
  // },

  stop: function (which) {
    var e = this;
    //清空计数器
    clearInterval(interval);
    //初始化当前位置因为onload给了一个选中状态
    var current = -1;
    var color = e.data.color;
    for (var i = 0; i < color.length; i++) {
      if (color[i] == 0.5) {
        current = i;
     
      }
    }
    //下标从1开始
    var index = current + 1;
    e.stopLuck(which, index, intime, 10);
  },
  /**
   * which:中奖位置
   * index:当前位置
   * time：时间标记
   * splittime：每次增加的时间 值越大减速越快
   */
  stopLuck: function (which, index, time, splittime) {
    var e = this;
    //值越大出现中奖结果后减速时间越长
  
    var color = e.data.color;
    setTimeout(function () {
      //重置当前选中位置
      if (index > 7) {
        index = 0;
        color[7] = 1
      } else if (index != 0) {
        color[index - 1] = 1
      }
      //当前位置为选中状态
      color[index] = 0.5
      e.setData({
        color: color,
      })
      //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
      //直到旋转至中奖位置
      if (time < 400 || index != which) {
        //越来越慢
        splittime++;
        time += splittime;
        //当前位置+1
        index++;
        e.stopLuck(which, index, time, splittime);
      } else {
        //1秒后显示弹窗
        setTimeout(function () {
          console.log('aaa');
          //中奖
          wx.showModal({
            title: '提示',
            content:  e.data.luckPoint ,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                   //当前位置为选中状态
                 color[which] = 1   //结束后把中奖改为没被选中
    
                //设置按钮可以点击
                e.setData({
                  btnconfirm: '/images/zhuangpan/dianjichoujiang.png',
                  clickLuck: 'clickLuck',
                  color: color,
                })
                e.loadAnimation();
              }
            }
          })
        }, 1000);
      }
    }, time);
    // console.log(time);
  },
  //进入页面时缓慢切换
  loadAnimation: function () {
    var e = this;
    var index = 0;
    // if (interval == null){
    interval = setInterval(function () {
      if (index > 7) {
        index = 0;
        e.data.color[7] = 1
      } else if (index != 0) {
        e.data.color[index - 1] = 1
      }
      e.data.color[index] = 0.5
      e.setData({
        color: e.data.color,
      })
      index++;
    }, 1000);
    // }  
  },
jilu(){
wx.navigateTo({
  url: './child/price_detail/price_detail?openid=' + this.data.openid
})
}
})
